const fs = require("fs");
const path = require("path");
const run = require("./run.js");
const execShPromise = require("exec-sh").promise;

const generateTagVersion = async () => {
  const crypto = require("crypto");
  const hash = crypto.createHash("md5");
  // 根据时间戳生成唯一hash
  hash.update(Date.now().toString());

  const version = hash.digest("hex").slice(0, 8);
  return version;
};

const TAGS = {
  prod: "prod",
  dev: "dev",
};
const publishAll = async (tag, allPkgList, pkgcwd) => {
  //   console.log('tag, allPkgList, pkgcwd', tag, allPkgList, pkgcwd);
  if (tag === TAGS.prod) {
    return execShPromise(`npm publish`);
  }
  //   const newVersion = await generateTagVersion();
  for (const pkg of allPkgList) {
    const { name } = pkg;
    const pkgName = name.split("/")[1];
    const pkgPath = path.resolve(pkgcwd, pkgName);
    // const newPkgJson = {
    //   ...pkg,
    //   version: `${pkg.version}-${tag}.${newVersion}`,
    // };
    // // 更改version
    // fs.writeFileSync(
    //   path.resolve(pkgPath, "./package.json"),
    //   JSON.stringify(newPkgJson, null, 2)
    // );
    await run("pnpm version patch", `${pkgPath}`);
    await run(`npm publish --tag=${tag}`, `${pkgPath}`);
  }
};

exports.publishAll = publishAll;
